const tableData = {
    columns: [
        { name: "二级分类", width: "20%" },
        { name: "分值", width: "10%" },
        { name: "标准调整", width: "50%" },
        { name: "评分", width: "20%" }  // 新增评分列
    ],
    rows: [
        {
            '二级分类': '交付及时性',
            '分值': "<span class='pj-hisense-badge pj-badge-green'>100</span>",
            '标准调整': `<ul>
            <li class="pj-li">1、支撑项目紧急需求，优于项目进度约定交付时间，进行交付，100分。</li>
            <li class="pj-li">2、按照项目进度约定交付时间，进行交付。80分。</li>
            <li class="pj-li">3、未按照品类/合同约定交付时间，未造成影响，60分。</li>
            <li class="pj-li">4、未按照品类/合同约定交付时间，对我司项目造成一定影响，例施工进度造成实施影响，30分。</li>
            <li class="pj-li">5、未按照品类/合同约定交付时间，对我司项目造成严重影响，例客户投诉函件、罚款单等，0分。</li>
            </ul>`
        },
        {
            '二级分类': '交付质量',
            '分值': "<span class='pj-hisense-badge pj-badge-green'>100</span>",
            '标准调整': `<ul>
            <li class="pj-li">1、未出现质量问题，且配合海信完成业主特定需求。100分。</li>
            <li class="pj-li">2、未出现质量问题。80分。</li>
            <li class="pj-li">3、出现质量问题，未造成影响，60分。</li>
            <li class="pj-li">4、出现质量问题，对我司项目造成一定影响，例施工进度、客户满意度（未发函、罚款）造成实施影响，30分。</li>
            <li class="pj-li">5、出现质量问题，对我司项目造成严重影响，例客户投诉函件、罚款单、安全问题等，0分。</li>
            </ul>`
        }
    ]
}
$NG.AllReady(function (page, { useDataIndexChange, useBeforeClick, useValuesChange, useClick, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_sub_cnt_m");
    const dgrid1 = $NG.getCmpApi("p_form_sub_cnt_d1");
    const dgrid2 = $NG.getCmpApi("p_form_sub_cnt_d2");
    const dgrid3 = $NG.getCmpApi("p_form_sub_cnt_d3");
    if (page.oType == "add") {
        getGzZc()
        cntMFilter()
        getPtInfoByPhid()
        getCntCount("p_form_sub_cnt_m", "u_cnt_name", async () => {
            const ht = $NG.getCmpApi("p_form_sub_cnt_m").getItem("u_cnt_name").getValue()
            cntMFilter()
            getCntMInfoByPhid()
            getFbCntBgAmt()
            getCntDetil()
            await getFbhtjsWlTotalamt()
            FBJG(ht)
            getFbjsAmt()
            getFbCntJsInfo()
            setTitle()
            getFbCntJSSbqdQty()
            getFbjsjfDetail()

        })
    }
    const gridToolbar = $NG.getCmpApi("toolbar_p_form_sub_cnt_d1")
    gridToolbar.getItem('imp').setProps({ children: '引用分包清单明细' })
    const gridToolbar1 = $NG.getCmpApi("toolbar_p_form_sub_cnt_d2")
    gridToolbar1.getItem('imp').setProps({ children: '引用分包奖罚单明细' })
    function hideDjyy() {
        try {
            console.log(`执行力`,);
            $NG.updateUI((updater) => {
                updater.toolbar.editbar.p_form_sub_cnt_d1.imp.setProps({
                    hidden: mstform.getItem("u_js_type").getValue() == '2'
                })
            })
            setTimeout(() => {
                try {
                    gridToolbar.getItem('imp').setProps({ children: '引用分包清单明细' })
                } catch (e) {
                    console.log('不重要的错误' + e)
                }
            }, 500)
        } catch (e) {
            console.log(`没找到单据引用按钮`, e);
        }
    }
    // 重写评分提交
    window.$PJ.submit = function (datas) {
        try {
            datas.forEach(item => {
                let key = ''
                switch (item.productId) {
                    case '交付及时性':
                        key = 'u_jfjs_score'
                        break
                    case '服务响应':
                        key = 'u_fwxy_score'
                        break
                    case '交付质量':
                        key = 'u_jfzl_score'
                        break
                    case '资源投入':
                        key = "u_zytr_score"
                        break
                }
                mstform.getItem(key).setValue((Number(item.score) || 0))
            })
            window.$PJ.onHiddenPj()
        } catch (e) {
            console.log(`发生异常`, e);
        }
    }
    useBeforeClick(() => {
        let temp = null
        let lock = true
        console.log(`当前类型`, mstform.getItem("u_js_type").getValue());
        try {
            switch (mstform.getItem("u_js_type").getValue()) {
                case '1':
                    temp = {...tableData}
                    temp.rows = [...tableData.rows]
                    temp.rows = temp.rows.filter(item => item['二级分类'] != '交付及时性')
                    if (!mstform.getItem("u_jfzl_score").getValue()) {
                        lock = false
                    }
                    break
                case '2':
                    temp = {...tableData}
                    if (!mstform.getItem("u_jfjs_score").getValue() || !mstform.getItem("u_jfzl_score").getValue()) {
                        lock = false
                    }
                    break
            }
            if (!lock) {
                window.$PJ.pjGenerateTable(temp)
                window.$PJ.onShowPj()
            }
        } catch (e) {
            $NG.alert("保存发生异常，二开")
            return false
        }
        return lock
    }, "save")

    hideKey()
    function hideKey() {
        const type = mstform.getItem("u_js_type").getValue()
        if (!type) return
        const jsHide = ["u_sb_amt", "u_hd_amt", "u_hj_amt", "u_hj_rate", "u_jf_amt", "u_wzkk_amt"]
        const gcHide = ["u_syjsje", "u_sb_total_amt", "u_hd_total_amt", "u_hj_total_amt", "u_hj_rate_total", "u_jf_total_amt", "u_wzkk_total_amt"]
        const gcHide_d = ["u_yshd_qty", "u_yshd_amt", "u_yshj_qty"]
        let lock = true
        switch (type) {
            case '1':
                lock = true
                break
            case '2':
                lock = false
                break

        }
        jsHide.forEach(item => {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_sub_cnt_m[item].setProps({
                    hidden: !lock
                })
            })
        })
        gcHide.forEach(item => {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_sub_cnt_m[item].setProps({
                    hidden: lock
                })
            })
        })

        gcHide_d.forEach(item => {
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_sub_cnt_d1[item].setProps({
                    hidden: lock
                })
            })
        })
    }
    //hidden
    $NG.updateUI((updater) => {
        updater.editbar.p_form_sub_cnt_d2.imp.setProps({
            hidden: true
        })
    })
    $NG.updateUI((updater) => {
        updater.editbar.p_form_sub_cnt_d3.imp.setProps({
            hidden: true
        })
    })
    $NG.getCmpApi("toolbar_top").getItem("imp").setHidden();
    //hidden
    function setTitle() {
        const u_cnt_name = (String(mstform.getItem("u_cnt_name").getText()) || 0)
        const gzdy = (String(mstform.getItem("phid_cycle").getText()) || 0)
        const u_js_type = (String(mstform.getItem("u_js_type").getText()) || 0)
        $NG.updateState((updater) => {
            updater.data.p_form_sub_cnt_m.setProps({
                bill_name: `${u_cnt_name}${gzdy}${u_js_type}`
            })
        })
    }
    useValuesChange(async ({ args }) => {
        console.log(`监听合同变化`, args);
        const _data = args[0]
        const ht = _data.u_cnt_name.value;
        cntMFilter()
        getCntMInfoByPhid()
        getFbCntBgAmt()
        //getPtInfoByPhid_cnt()
        getCntDetil()
        await getFbhtjsWlTotalamt()
        FBJG(ht)
        getFbjsAmt()
        getFbCntJsInfo()
        setTitle()
        getFbCntJSSbqdQty()
        getFbjsjfDetail()
    }, "p_form_sub_cnt_m.u_cnt_name")

    useValuesChange(({ args }) => {
        try {
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    u_cnt_name: undefined
                })
            })
        } catch (e) { }
        getPtInfoByPhid()
        cntMFilter()
        getCntDetil()
        setTitle()
        getFbhtjsWlTotalamt()
        getCntCount("p_form_sub_cnt_m", "u_cnt_name", async () => {
            const ht = $NG.getCmpApi("p_form_sub_cnt_m").getItem("u_cnt_name").getValue()
            cntMFilter()
            getCntMInfoByPhid()
            getFbCntBgAmt()
            getCntDetil()
            await getFbhtjsWlTotalamt()
            FBJG(ht)
            getFbjsAmt()
            getFbCntJsInfo()
            setTitle()
            getFbCntJSSbqdQty()
            getFbjsjfDetail()
        })
    }, "p_form_sub_cnt_m.phid_pc")

    useValuesChange(async ({ args }) => {
        await dgrid1.clearRows()
        getCntDetil()
        hideDgridKey()
        hideDjyy()
        setTitle()
        hideKey()
        getFbjsjfDetail()
    }, "p_form_sub_cnt_m.u_js_type")
    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_sub_cnt_d1")
    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_sub_cnt_d2")
    useClick(() => {
        sumAmt()
    }, 'addrow')
    useClick(() => {
        sumAmt()
    }, 'deleterow')

    useDataIndexChange(({ args }) => {
        // args[0].u_bqhd_qty = args[0].u_bqjl_qty
        sumAmt()
        console.log(`计量数量监听`, args[0]);
        dgrid1.refreshView()
    }, "u_bqjl_qty")

    const dgrid3Key = ["u_bzshl", "u_htshl", "u_bzyl", "u_prc", "u_sy_qty", "u_kc_qty", "u_wzsb_qty"]
    dgrid3Key.forEach(item => {
        useDataIndexChange(({ args }) => {
            const row = args[0]
            console.log(`表体3监听计算`,);
            dgrid3.refreshView()
            sumAmt()
            dgrid3.refreshView()
        }, item)
    })

    // 跳转模板导入
    const paramArr = [
        {
            condition: () => {
                return mstform.getItem("u_js_type").getValue() == '1'
            },
            param: `{"reportId":"8570000000000032","linkParams":[{"paramKey":"phid","dataSetId":"8570000000000035","paramValueSource":"user_input","operator":"like","fieldType":null,"paramValue":"${mstform.getValues().phid}"}],"sheetKey":"0","fetchType":0}`,
        },
        {
            condition: () => {
                return mstform.getItem("u_js_type").getValue() == '2'
            },
            param: `{"reportId":"8570000000000035","linkParams":[{"paramKey":"phid","dataSetId":"8570000000000036","paramValueSource":"user_input","operator":"like","fieldType":null,"paramValue":"${mstform.getValues().phid}"}],"sheetKey":"0","fetchType":0}`
        }
    ]
    toMbIn("p_form_sub_cnt_m", "p_form_sub_cnt_d1", "to_template", paramArr, () => {
        let lock = true
        if (!mstform.getItem("u_js_type").getValue()) {
            $NG.alert("结算类型不能为空")
            lock = false
        }
        return lock
    })
    /**
     * 模板导出按钮添加
     * 参数模板
     * [{
              condition:()=>{
                  return mstform.getItem("u_js_type").getValue() == '1'
              },
              param:``,
  }],
    */
    function toMbIn(tabelHeader, tableName, btnId, params, premise) {
        const toolbar_dgrid = $NG.getCmpApi("toolbar_" + tableName)
        toolbar_dgrid.insert({
            id: btnId,
            text: "导出",
            iconCls: "icon-InsertRow",
        });
        useClick(async function ({ args }) {
            if (premise && !premise()) {
                return false
            }
            // 获取项目选择的值
            const phid = $NG.getCmpApi(tabelHeader).getValues().phid; // 动态获取的项目选择值

            // 构造 URL 参数
            const url = window.location.href;
            const protocol = $NG.split(url, "/")[0]; // 协议类型
            const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
            const url_path = "/report/index.html#/tableDesign/TableManager/preview"; // 路径
            let param = null
            if (params instanceof Array) {
                params.forEach(item => {
                    const bool = item.condition()
                    if (bool) {
                        if (item.param instanceof Object) {
                            param = { ...item.param }
                        } else {
                            param = JSON.parse(item.param)
                        }
                    }
                })
            } else {
                if (params instanceof Object) {
                    param = params
                } else {
                    param = JSON.parse(params)

                }
            }
            for (let key in param) {
                if (param[key] instanceof Object) {
                    param[key] = JSON.stringify(param[key])
                }
                if (key == 'queryParamList') {
                    param['linkParams'] = param['queryParamList']
                    delete param['queryParamList']
                } else if (key == 'reportId') {
                    param['rep_id'] = param['reportId']
                    delete param['reportId']
                }
            }
            const query_params = new URLSearchParams(param).toString(); // 使用 URLSearchParams 来构造查询参数

            // 打开报表并传递参数
            console.log(`跳转连接`, `${protocol}//${url_domain}${url_path}?${query_params}`);
            $NG.open(`${protocol}//${url_domain}${url_path}?${query_params}`, { AppTitle: "模板导出" });
        }, btnId);
    }

    function sumAmt() {
        console.log(`计算被调用`,);
        if (page.oType == 'view') return
        const arr1 = dgrid1.getRows()
        const arr2 = dgrid2.getRows()
        const arr3 = dgrid3.getRows()

        arr1.forEach((item, index) => {
            /*if ((Number(item.u_bqhd_qty) || 0) > (Number(item.u_bqjl_qty) || 0)) {
                $NG.alert("当前本期核定数量大于本期计量数量，请重新填写")
                item.u_bqhd_qty = 0
            }
            if (((Number(item.u_cnt_qty) || 0) - (Number(item.u_yjs_qty) || 0)) < (Number(item.u_bqjl_qty) || 0)) {
                item.u_bqjl_qty = 0
                $NG.alert("本期计量数量不得大于合同清单剩余数量（清单-已结算）")
            }*/
            // 本期核定数量
            console.log(!window.__cache_lsz_d1[item.u_cnt_qd_name] || !item.u_cnt_qd_name);
            if (!window.__cache_lsz_d1[item.u_cnt_qd_name] || !item.u_cnt_qd_name || !window.__cache_lsz_d1_qty[item.u_cnt_qd_name]) {
                getFbCntJs(item.u_cnt_qd_name, (amt, qty) => {
                    window.__cache_lsz_d1[item.u_cnt_qd_name] = amt
                    window.__cache_lsz_d1_qty[item.u_cnt_qd_name] = qty
                    // item.u_bq_hjqty = ((Number(item.u_bqjl_qty) || 0) - (Number(item.u_bqhd_qty)) || 0)
                    // item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0)) < 0 ? 0 : ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                    // item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0) * (Number(item.u_bqhd_qty) || 0)
                    // item.u_ljjs_amt_vat = Number(amt) + Number(item.u_bqjs_amt_vat)
                    // item.u_lj_hjqty = Number(qty) + Number(item.u_bqhd_qty)
                })
            } else {
                // item.u_bq_hjqty = ((Number(item.u_bqjl_qty) || 0) - (Number(item.u_bqhd_qty)) || 0)
                // item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0)) < 0 ? 0 : ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                // item.u_lj_hjqty = (Number(window.__cache_lsz_d1_qty[item.u_cnt_qd_name]) || 0) + (Number(item.u_bqhd_qty) || 0) 
            }
            item.u_hd_amt = (Number(item.u_bqhd_qty) || 0) * (Number(item.u_cnt_prc_vat) || 0)
            item.u_ljjl_qty = (Number(item.u_yjs_qty) || 0) + (Number(item.u_bqjl_qty) || 0)
            item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0) * (Number(item.u_bqjl_qty) || 0)
            item.u_ljjs_amt_vat = (Number(window.__cache_lsz_d1[item.u_cnt_qd_name]) || 0) + (Number(item.u_bqjs_amt_vat) || 0)
            item.u_lj_hd_amt = (Number(item.u_cnt_prc_vat) || 0) * ((Number(item.u_yjs_qty) || 0) + (Number(item.u_bqhd_qty) || 0))
            console.log(`缓存检查`, window._catch_sbqdqty);
            item.u_ljhd_qty = (Number(item.u_yjs_qty) || 0) + (Number(item.u_bqhd_qty) || 0)
            item.u_bq_hjqty = ((Number(item.u_bqjl_qty) || 0) - (Number(item.u_bqhd_qty)) || 0)
            item.u_yshj_qty = ((Number(item.u_yjs_qty) || 0) + (Number(item.u_bqjl_qty) || 0)) - (Number(item.u_yshd_qty) || 0)
            let _temp_total = 0
            /*if(item.u_ljhd_qty > item.u_cnt_qty){
                $NG.alert("累计核定数量不能大于合同清单数量！！！")
                item.u_bqhd_qty = 0
                item.u_ljhd_qty = item.u_yjs_qty
            }*/
            window._catch_sbqdqty.forEach(el => {
                if (el.u_sbqd_name == item.u_sbqd_name) {
                    console.log(`已找到累计`, el);
                    _temp_total = (Number(el.ljhj_qty) || 0)
                    item.u_yjs_qty = (Number(el.hdtotal_qty) || 0)
                }
            })
            console.log(`数量检查`, _temp_total, (Number(item.u_bq_hjqty) || 0));
            item.u_lj_hjqty = _temp_total + (Number(item.u_bq_hjqty) || 0)
            //税额
            item.u_tax_amt = ((Number(item.u_cnt_prc_vat) || 0) - (Number(item.u_cnt_prc) || 0)) * (Number(item.u_bqhd_qty) || 0)
            item.u_yshd_amt = (Number(item.u_yshd_qty) || 0) * (Number(item.u_cnt_prc_vat) || 0)
        })

        //计算合同结算金额
        let d1data = arr1.reduce((value, item) => {
            value[0] += (Number(item.u_bqjs_amt_vat) || 0)
            value[1] += (Number(item.u_hd_amt) || 0)
            value[2] += (Number(item.u_yshd_amt) || 0)
            return value
        }, [0, 0, 0])
        //计算合同结算金额（包含奖罚单）
        let cnt_amt_in_jf = arr2.reduce((value, item) => {
            if (item.u_jf_lx == '2') {
                value += (Number(item.u_amt_vat) || 0)
            } else {
                value -= (Number(item.u_amt_vat) || 0)
            }
            return value
        }, 0)
        // 汇总超额物料金额
        let sb_wl_amt = 0
        let cnt_wl_amt = arr3.reduce((value, row) => {
            //相关计算逻辑
            row.u_sy_qty = row.u_ly_qty - row.u_kc_qty
            row.u_ch_qty = row.u_sy_qty - ((Number(row.u_bzyl) || 0) * (1 + (Number(row.u_bzshl) || 0)))
            row.u_out_je = (Number(row.u_ch_qty) || 0) <= 0 ? 0 : row.u_ch_qty * row.u_prc
            row.u_yk_out_je = (Number(row.u_out_je) || 0) && (Number((Number(row.u_out_je) || 0) - (Number(row.u_ykc_out_je) || 0)) || 0)
            row.u_wzsb_chqty = (Number(row.u_sy_qty) || 0) - ((Number(row.u_wzsb_qty) || 0) * (1 + (Number(row.u_bzshl) || 0)))
            row.u_sb_out_amt = (Number(row.u_wzsb_chqty) || 0) <= 0 ? 0 : row.u_wzsb_chqty * row.u_prc
            row.u_wzsb_ykamt = (Number(row.u_wzsb_chqty) || 0) && (Number((Number(row.u_sb_out_amt) || 0) - (Number(row.u_wzsb_alamt) || 0)) || 0)
            value += Number(row.u_yk_out_je)
            sb_wl_amt += (Number(row.u_wzsb_ykamt) || 0)
            return value
        }, 0)
        console.log(`执行中sunAmt`, cnt_wl_amt);
        let cnt_amt = d1data[0]
        let hdamttotal = d1data[1]
        let yshdamttotal = d1data[2]
        switch (mstform.getItem("u_js_type").getValue()) {
            case '1':
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_jsamt_vat: cnt_amt,
                        u_jsamt_total: cnt_amt - cnt_amt_in_jf - (Number(cnt_wl_amt) || 0),
                        u_syjsje: cnt_amt - cnt_amt_in_jf - (Number(cnt_wl_amt) || 0),
                        u_ljjsze: (Number(window._catch_cnt_js_amt + (cnt_amt - cnt_amt_in_jf - cnt_wl_amt)) || 0),
                        u_ljjs_amt: (Number(window._catch_cnt_amt + cnt_amt) || 0),
                        u_jf_amt: cnt_amt_in_jf,
                        u_wzkk_amt: cnt_wl_amt,
                        u_sb_amt: cnt_amt - cnt_amt_in_jf - sb_wl_amt,
                        u_hd_amt: hdamttotal - cnt_amt_in_jf - cnt_wl_amt,
                        u_syjsje: hdamttotal - cnt_amt_in_jf - cnt_wl_amt,
                        u_hj_amt: cnt_amt - cnt_amt_in_jf - sb_wl_amt - (hdamttotal - cnt_amt_in_jf - cnt_wl_amt),
                        u_hj_rate: (cnt_amt - cnt_amt_in_jf - sb_wl_amt - (hdamttotal - cnt_amt_in_jf - cnt_wl_amt)) / cnt_amt,

                    })
                })
                break;
            case '2':
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_jsamt_vat: cnt_amt,
                        u_jsamt_total: cnt_amt - cnt_amt_in_jf - (Number(cnt_wl_amt) || 0),
                        u_syjsje: cnt_amt - cnt_amt_in_jf - (Number(cnt_wl_amt) || 0),
                        u_ljjsze: (Number(window._catch_cnt_js_amt + (cnt_amt - cnt_amt_in_jf - cnt_wl_amt)) || 0),
                        u_ljjs_amt: (Number(window._catch_cnt_amt + cnt_amt) || 0),
                        u_jf_amt: cnt_amt_in_jf,
                        u_wzkk_amt: cnt_wl_amt,
                        u_sb_amt: cnt_amt - cnt_amt_in_jf - sb_wl_amt,
                        u_hd_amt: hdamttotal - (cnt_amt_in_jf - cnt_wl_amt),
                        u_syjsje: hdamttotal - (cnt_amt_in_jf - cnt_wl_amt),
                        u_hj_amt: cnt_amt - cnt_amt_in_jf - sb_wl_amt - (hdamttotal - cnt_amt_in_jf - cnt_wl_amt),
                        u_hj_rate: (cnt_amt - cnt_amt_in_jf - sb_wl_amt - (hdamttotal - cnt_amt_in_jf - cnt_wl_amt)) / cnt_amt,
                        // 验收上报
                        u_sb_total_amt: cnt_amt + (Number(mstform.getItem("u_lj_gc_amt").getValue()) || 0),
                        // 验收核定
                        u_hd_total_amt: (yshdamttotal - cnt_amt_in_jf - cnt_wl_amt),
                        // 验收核减
                        u_hj_total_amt: (cnt_amt + (Number(mstform.getItem("u_lj_gc_amt").getValue()) || 0)) - (yshdamttotal - cnt_amt_in_jf - cnt_wl_amt),
                        u_hj_rate_total: ((cnt_amt + (Number(mstform.getItem("u_lj_gc_amt").getValue()) || 0)) - (yshdamttotal - cnt_amt_in_jf - cnt_wl_amt)) / (cnt_amt + (Number(mstform.getItem("u_lj_gc_amt").getValue()) || 0)),
                        u_jf_total_amt: cnt_amt_in_jf,
                        u_wzkk_total_amt: (Number(window._catch_cnt_amt_yk) || 0) + cnt_wl_amt,
                    })
                })
        }
        dgrid1.refreshView()
        dgrid2.refreshView()
        dgrid3.refreshView()
    }
    //获取累计合同结算金额
    getFbjsAmt()
    function getFbjsAmt() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        const u_cnt_name = mstform.getItem("u_cnt_name").getValue()
        $NG.execServer("getFbjsAmt", { u_cnt_name }, (res) => {
            console.log(`获取累计`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)
            window._catch_cnt_amt = _data.reduce((value, item) => {
                const el = item.extendObjects
                value += (Number(el.amt) || 0)
                return value
            }, 0)
            window._catch_cnt_amt_gc = _data.reduce((value, item) => {
                const el = item.extendObjects
                if (el.u_js_type == '1') {
                    value += (Number(el.amt) || 0)
                }
                return value
            }, 0)
            // 奖罚
            window._catch_cnt_amt_jf = _data.reduce((value, item) => {
                const el = item.extendObjects
                if (el.u_js_type == '1') {
                    value += (Number(el.jf_amt) || 0)
                }
                return value
            }, 0)
            // 应扣
            window._catch_cnt_amt_yk = _data.reduce((value, item) => {
                const el = item.extendObjects
                if (el.u_js_type == '1') {
                    value += (Number(el.yk_amt) || 0)
                }
                return value
            }, 0)
            // 核减
            window._catch_cnt_amt_hj = _data.reduce((value, item) => {
                const el = item.extendObjects
                value += (Number(el.hj_amt) || 0)
                return value
            }, 0)
            if (page.oType == 'add' || page.oType == 'edit') {
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_yjs_amt: _data.reduce((value, item) => {
                            const el = item.extendObjects
                            value += (Number(el.hd_amt) || 0)
                            return value
                        }, 0),
                        u_lj_gc_amt: _data.reduce((value, item) => {
                            const el = item.extendObjects
                            if (el.u_js_type == '1') {
                                value += (Number(el.hd_amt) || 0)
                            }
                            return value
                        }, 0)
                    })
                })
                setTimeout(() => {
                    sumAmt()
                }, 500)
            }
        })
    }

    //结算清单相关计算
    window.__cache_lsz_d1 = {}
    window.__cache_lsz_d1_qty = {}
    //获取项目信息
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    //【注意这里的表名不能为控件ID，必须要是表名】
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_pc_no: datas.pc_no,
                        //售前顾问
                        u_sqgw: {
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //项目经理
                        u_project_manager: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //区域中心
                        u_regional_center: {
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                    });
                });
            });
        }
    }

    // 获取分包结算已超耗金额
    window._catch_cnt_cc_amt = []
    getFbhtjsWlTotalamt()
    async function getFbhtjsWlTotalamt() {
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) { return }
        await $NG.execServer("getFbhtjsWlTotalamt", { cnt }, async function (res) {
            console.log(`查询物料超耗金额:${res.count}`, res);
            if (res.count == 0) return
            window._catch_cnt_cc_amt = JSON.parse(res.data).reduce((value, items) => {
                const item = items.extendObjects
                value.push(item)
                return value
            }, [])
        })
    }

    //获取结算明细
    function getFbCntJs(phid, fun) {
        if (!phid || !mstform.getItem("u_cnt_name").getValue()) { fun(0); return }
        $NG.execServer("getFbCntJs", { cnt_phid: mstform.getItem("u_cnt_name").getValue(), qd_phid: phid }, function (res) {
            console.log(`获取累计金额`, mstform.getItem("u_cnt_name").getValue(), phid, res);
            if (res.count == 0) {
                fun(0, 0)
            } else {
                const _data = JSON.parse(res.data)[0].extendObjects
                fun(_data.total_amt, _data.total_qty)
            }
            dgrid1.refreshView()
        })
    }

    //获取合同信息
    getCntMInfoByPhid()
    function getCntMInfoByPhid() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        console.log(`开始获取合同`);
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("u_cnt_name").getValue() },
            function (res) {
                if (res.count == 0) return
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_cnt_no: datas.pcm_no, //合同编码
                        u_fbcnt_nowamt: datas.cnt_sum_vat_fc, //合同价税合计
                        u_fbht_amt: datas.cnt_sum_vat_fc, //合同价税合计
                        u_fbht_amt: datas.init_cnt_amt,
                        //合同类型
                        pct_id: { value: datas.pct_id, label: datas.pct_name },
                        //甲方单位
                        u_dept_a: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        u_fbdw_manager: datas.user_supply_preson,
                        //乙方单位
                        u_yf_dept: {
                            value: datas.supply_id,
                            label: datas.supply_name,
                        },
                        u_remarks: datas.remarks,
                        u_fbdw_manager: datas.phid_senemp
                    });
                });
            }
        );
    }

    // 获取分包合同过程结算的奖罚信息
    page.oType == 'page' && getFbjsjfDetail()
    function getFbjsjfDetail() {
        const cnt = mstform.getItem("u_cnt_name").getValue()
        const type = mstform.getItem("u_js_type").getValue()
        if (type != '2') return
        if (!cnt) return
        $NG.execServer("getFbjsjfDetail", { cnt }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data).reduce((value, item) => {
                value.push(item.extendObjects)
                return value
            }, [])
            console.log(`奖罚明细打印`, _data);
            dgrid2.clearRows().then(() => {
                dgrid2.addRows([..._data])
            })
            sumAmt()
        })
    }
    //获取工作周期
    function getGzZc() {
        let _count = {}
        $NG.execServer("getInDate", {}, function (res) {
            console.log(`获取工作周期`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_cycle: {
                        label: _data.bill_name,
                        value: _data.phid
                    }
                })
            })
        })
    }
    // 获取分包合同变更的变更金额
    function getFbCntBgAmt() {
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) return
        $NG.execServer("getFbCntBgAmt", { cnt }, (res) => {
            if (res.coutn == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    u_fbcnt_bgamt: _data.total_bg_amt
                })
            })
        })
    }
    // 获取分包应付单的相应累计金额
    function getFbyfdTotalAmt() {
        const cnt = mstform.getItem("u_cnt_name").getValue()

        if (!cnt) return
        $NG.execServer("getFbyfdTotalAmt", { cnt }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    u_lj_fk_amt: _data.hd_total_amt
                })
            })
        })
    }
    // 计算2个日期之间得天数
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }
    async function getCntDetil() {
        console.log(mstform.getItem("u_js_type").getValue());
        // console.log(,mstform.getItem("u_js_type").getValue());
        if (!mstform.getItem("u_js_type").getValue() || !(mstform.getItem("u_js_type").getValue() == '2') || !mstform.getItem("u_cnt_name").getValue()) return
        await $NG.execServer("getCntDetail", { phid: mstform.getItem("u_cnt_name").getValue() }, async function (res) {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)
            console.log(`明细`, datas);
            await getFbCntJSSbqdQty()
            dgrid1.clearRows().then(() => {
                let _arr = []
                _arr = []
                datas.forEach(items => {
                    const item = items.extendObjects
                    let qty = 0
                    let yjsqty = 0
                    let ljhj_qty = 0
                    window._catch_sbqdqty.filter(el => {
                        if (el.u_sbqd_name == item.user_u_equipment_list_name) {
                            qty = el.qty
                            yjsqty = el.hdtotal_qty
                            ljhj_qty = el.ljhj_qty
                        }
                    })



                    if (true) {
                        _arr.push({
                            u_sbqd_no: item.user_u_equipment_list_no,
                            u_sbqd_name: item.user_u_equipment_list_name,
                            u_sbqd_name_EXName: item.user_u_equipment_list_name_exname,
                            itemid: item.phid_itemid,
                            itemno_EXName: item.itemno,
                            itemname: item.itemname,
                            u_cnt_qd_name: item.cntd_phid,
                            u_cnt_qd_name_EXName: item.item_name,
                            u_cnt_qd_no: item.item_no,
                            u_bqjl_qty: item.qty - yjsqty,
                            u_bqhd_qty: item.qty - yjsqty,
                            u_lj_hjqty: ljhj_qty,
                            u_yjs_qty: yjsqty,
                            u_ljhd_qty: (item.qty - yjsqty) + (yjsqty),
                            u_cnt_prc: item.prc_fc,
                            u_cnt_qty: item.qty,
                            u_cnt_prc_vat: item.prc_vat_fc,
                            u_bqjs_amt_vat: item.amt,
                            u_tax: item.taxrate,
                            u_tax_amt: item.taxamt

                        })
                    }

                })
                dgrid1.addRows(_arr).then(() => {
                    sumAmt()
                })
                dgrid1.refreshView()
                setTimeout(() => {
                    sumAmt()
                }, 500)
            })
        })
    }
    //获取项目信息
    function getPtInfoByPhid_cnt() {
        const mstform = $NG.getCmpApi("p_form_sub_cnt_m")
        $NG.execServer("getPtInfoByPhid_cnt", { phid_cnt: mstform.getItem("u_cnt_name").getValue() }, (res) => {
            console.log(`获取项目信息`, res);
            if (res.count === 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(datas);
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_pc: {
                        value: datas.pc_phid,
                        label: datas.pc_name
                    }
                })
            })
        })
    }

    // 表体部分字段隐藏
    hideDgridKey()
    function hideDgridKey() {
        const _arr = ['u_yshd_qty']
        console.log(`结算类型`, mstform.getItem("u_js_type").getValue());
        if (mstform.getItem("u_js_type").getValue() == '2') {
            _arr.forEach((item) => {
                $NG.updateUI((updater) => {
                    // console.log(`hiden`,updater.editGrid.p_form_sub_cnt_d1[item]);
                    // if (updater.editGrid.p_form_sub_cnt_d1[item]) {
                    updater.editGrid.p_form_sub_cnt_d1[item].setProps({
                        hidden: false
                    })
                    // }
                })
            })
        } else {
            _arr.forEach((item) => {
                $NG.updateUI((updater) => {
                    // if (updater.editGrid.p_form_sub_cnt_d1[item]) {
                    updater.editGrid.p_form_sub_cnt_d1[item].setProps({
                        hidden: true
                    })
                    // }
                })
            })
        }
    }
    // 获取合同累计含奖罚单结算金额
    getFbCntJsInfo()
    function getFbCntJsInfo() {
        window._catch_cnt_js_amt = 0
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) return
        $NG.execServer("getFbCntJsInfo", { cnt }, (res) => {
            console.log(`获取合同累计结算信息`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            window._catch_cnt_js_amt = (Number(_data.total_cntamt) || 0)
            if (page.oType == 'add' || page.oType == 'edit') {
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_yjs_jfd_amt: (Number(_data.total_cntamt) || 0)
                    })
                })
            }
        })
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log("过滤参数检查", updater);
            updater.fieldSetForm.p_form_sub_cnt_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        phid_pc: $NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue(),
                        bill_type: 4
                    },
                }),
            });
        });
    }
    //物资清单获取
    function FBJG(htvalue) {
        dgrid3.clearRows();
        $NG.execServer("FBJS_JG_info", { ht: htvalue }, function (res) {
            console.log(`获取物料明细`, res);
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            var gridArr = []; // 定义表体数组
            var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
            for (var i = 0; i < gridCount; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {};

                gridObj.u_item_name = data[i].extendObjects.phid_item;
                gridObj.u_item_name_EXName = data[i].extendObjects.itemname
                gridObj.u_spec = data[i].extendObjects.spec;
                gridObj.u_unit = data[i].extendObjects.msunit;
                gridObj.u_unit_EXName = data[i].extendObjects.msname;
                gridObj.u_prc = data[i].extendObjects.prc_vat;
                gridObj.u_bzshl = data[i].extendObjects.bzshl;
                gridObj.u_htshl = data[i].extendObjects.htshl;
                gridObj.u_ly_qty = data[i].extendObjects.cksl;
                // gridObj.u_kc_qty = data[i].extendObjects.rest_qty;
                // gridObj.u_sy_qty = data[i].extendObjects.cksl;
                window._catch_cnt_cc_amt.forEach(el => {
                    if (data[i].extendObjects.phid_item == el.item_name) {
                        gridObj.u_ykc_out_je = el.total_amt,
                            gridObj.u_wzsb_alamt = el.sb_total_amt
                    }
                })
                gridArr.push(gridObj);
            }
            // 清空表格内容（放在循环外部）

            dgrid3.addRows(gridArr);
            dgrid3.refreshView();
        });
    }
    // 获取设备清单已结算数量
    getFbCntJSSbqdQty()
    async function getFbCntJSSbqdQty() {
        window._catch_sbqdqty = []
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) return
        await $NG.execServer("getFbCntJSSbqdQty", { cnt }, function (res) {
            console.log(`获取设备清单项目`, res);
            if (res.count == 0) return
            window._catch_sbqdqty = JSON.parse(res.data).reduce((value, item) => {
                value.push({
                    ...item.extendObjects
                })
                return value
            }, [])
        })
    }

});

function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 4, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        console.log(`当前项目合同数量`, res);
        switch (res.count) {
            case 0:
                return;
            case 1:
                const datas = JSON.parse(res.data)[0].extendObjects;
                const temp_map = {};
                temp_map[key] = datas.phid;
                temp_map[`${key}_EXName`] = datas.bill_name;
                $NG.updateState((updater) => {
                    updater.data[table].setProps({
                        ...temp_map,
                    });
                    setTimeout(() => {
                        if (fun) {
                            fun();
                        }
                    }, 200);
                });
        }
    });
}


initPjWindows(tableData, "二级分类")
function initPjWindows(d, k) { const s = `<style>:root{--pj-hisense-green:#00aaa6;--pj-hisense-light:#e8f5e9;--pj-hisense-dark:#00aaa6;}.pj-body{display:none;background:rgba(0,0,0,0.34);position:fixed;z-index:999;overflow:auto;font-family:"Helvetica Neue",Arial,sans-serif;padding:30px;width:100vw;height:100vh;}@keyframes bigBox{0%{width:0;transform:scaleY(0)}100%{width:70vw;transform:scaleY(1)}}.pj-li{list-style:none;padding:2px;}.pj-hisense-container{animation:bigBox 0.2s linear;width:70vw;margin:0 auto;padding:30px;background-color:#fff;border-radius:15px;}.pj-hisense-table{width:100%;border-collapse:separate;border-spacing:0;background:white;border-radius:12px;overflow:hidden;box-shadow:0 6px 20px rgba(0,168,98,0.1);}.pj-hisense-table thead tr{background:linear-gradient(135deg,var(--pj-hisense-green),var(--pj-hisense-dark));color:white;text-align:left;font-size:12px;}.pj-hisense-table th{padding:18px 15px;font-weight:600;letter-spacing:0.5px;position:relative;}.pj-hisense-table th:not(:last-child)::after{content:"";position:absolute;right:0;top:20%;height:60%;width:1px;background:rgba(255,255,255,0.3);}.pj-hisense-table td{padding:15px;border-bottom:1px solid #e0ece5;color:#333;font-size:10px;}.pj-hisense-table tbody tr:nth-child(even){background-color:var(--pj-hisense-light);}.pj-hisense-table tbody tr:last-child td{border-bottom:none;}.pj-hisense-table tbody tr:hover{background-color:rgba(0,168,98,0.08);transition:all 0.3s ease;}.pj-hisense-badge{display:inline-block;padding:4px 12px;border-radius:16px;font-size:12px;font-weight:600;}.pj-badge-green{background-color:rgba(0,168,98,0.15);color:var(--pj-hisense-dark);}.pj-badge-blue{background-color:#e3f2fd;color:#1976d2;}.pj-hisense-btn{padding:10px 20px;background:var(--pj-hisense-green);color:white;border:none;border-radius:6px;cursor:pointer;font-weight:500;transition:all 0.2s;margin-left:10px;}.pj-hisense-btn:hover{background:var(--pj-hisense-dark);transform:translateY(-1px);box-shadow:0 2px 8px rgba(0,168,98,0.3);}.pj-status-active{color:var(--pj-hisense-green);font-weight:600;position:relative;padding-left:20px;}.pj-status-active::before{content:"";position:absolute;left:0;top:50%;transform:translateY(-50%);width:12px;height:12px;background:var(--pj-hisense-green);border-radius:50%;}.pj-status-inactive{color:#f44336;font-weight:600;}.pj-table-caption{font-size:24px;color:var(--pj-hisense-dark);margin-bottom:20px;font-weight:600;display:flex;align-items:center;}.pj-table-caption::before{content:"";display:inline-block;width:8px;height:24px;background:var(--pj-hisense-green);margin-right:12px;border-radius:4px;}.pj-input-group{margin-bottom:20px;display:flex;}.pj-hisense-input{padding:10px 15px;border:1px solid #ddd;border-radius:6px;flex-grow:1;font-size:16px;transition:border 0.3s;}.pj-hisense-input:focus{outline:none;border-color:var(--pj-hisense-green);box-shadow:0 0 0 2px rgba(0,168,98,0.2);}.pj-table-footer{margin-top:20px;display:flex;justify-content:flex-end;}.pj-row-input{padding:8px 12px;border:1px solid #ddd;border-radius:4px;margin-right:10px;width:100px;}.pj-score-input{padding:8px;border:1px solid #ddd;border-radius:4px;width:80px;}</style>`, m = `<div class="pj-body"><div class="pj-hisense-container"><div class="pj-table-caption">评价标准</div><div id="pj-tableContainer"></div><div class="pj-table-footer"><button id="pj-getAllScoresBtn" class="pj-hisense-btn">提交</button></div></div></div>`; document.body.insertAdjacentHTML("afterbegin", m), document.head.insertAdjacentHTML("beforeend", s); const h = () => document.querySelector(".pj-body").style.display = "none", w = () => document.querySelector(".pj-body").style.display = "block"; document.querySelector(".pj-body").addEventListener("click", e => { if (e.target === e.currentTarget) h() }); function g(data) { let t = `<table class="pj-hisense-table"><thead><tr>`; data.columns.forEach(c => t += `<th style="width:${c.width}">${c.name}</th>`), t += `</tr></thead><tbody>`, data.rows.forEach((r, i) => { t += `<tr data-row-index="${i}">`, data.columns.forEach(c => { if (c.name === "评分") t += `<td><input type="text" class="pj-score-input" data-row-id="${r[k]}" placeholder="输入评分"></td>`; else { const v = r[c.name] || ""; t += `<td>${v}</td>` } }), t += `</tr>` }), t += `</tbody></table>`, document.getElementById("pj-tableContainer").innerHTML = t } function a() { return [...document.querySelectorAll(".pj-score-input")].map(e => ({ productId: e.getAttribute("data-row-id"), score: e.value })) } g(d), document.getElementById("pj-getAllScoresBtn").addEventListener("click", e => { const s = a(); try { window.$PJ.submit(s) } catch (e) { alert("提交函数未被重写，window.$PJ.submit") } console.log("所有评分数据：", s) }), window.$PJ = window.$PJ || {}, Object.assign(window.$PJ, { pjGenerateTable: g, onShowPj: w, onHiddenPj: h }) }
